const Promise = require('bluebird');
const excel = require('node-excel-export');
const apis = {};

/**
 * 用户相关Api
 */
const analysesV1 = require('./v1/analyses');
Object.assign(apis, {
    /**
     * 用户统计分析
     */
    '/v1/analyses/dashboard': {
        permission: {object_type: 'analyses', action_type: 'browse'},
        handler: analysesV1.dashboard
    },
    '/v1/analyses/orders_data': {
        permission: {object_type: 'analyses', action_type: 'browse'},
        handler: analysesV1.ordersData
    },
    '/v1/analyses/users_data': {
        permission: {object_type: 'analyses', action_type: 'browse'},
        handler: analysesV1.usersData
    },
    '/v1/analyses/withdraws_data': {
        permission: {object_type: 'analyses', action_type: 'browse'},
        handler: analysesV1.withdrawsData
    }
});

/**
 * 用户相关Api
 */
const searchsV1 = require('./v1/searchs');
const viewsV1 = require('./v1/views');
const textsV1 = require('./v1/texts');
Object.assign(apis, {
    /**
     * 用户搜索
     */
    '/v1/searchs/browse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: searchsV1.browse
    },
    /**
     * 用户浏览
     */
    '/v1/views/browse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: viewsV1.browse
    },
    /**
     * 用户文本
     */
    '/v1/texts/browse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: textsV1.browse
    }
});

/**
 * 商品相关Api
 */
const categoriesV1 = require('./v1/categories');
const goodsesV1 = require('./v1/goodses');
Object.assign(apis, {
    /**
     * 商品类别
     */
    '/v1/categories/tree': {
        permission: {object_type: 'goodses', action_type: 'browse'},
        handler: categoriesV1.tree
    },
    /**
     * 商品
     */
    '/v1/goodses/browse': {
        permission: {object_type: 'goodses', action_type: 'browse'},
        handler: goodsesV1.browse
    },
    '/v1/goodses/load': {
        permission: {object_type: 'goodses', action_type: 'browse'},
        handler: goodsesV1.load
    },
    '/v1/goodses/add': {
        permission: {object_type: 'goodses', action_type: 'add'},
        handler: goodsesV1.add,
        table: 'Goodses'
    },
    '/v1/goodses/edit': {
        permission: {object_type: 'goodses', action_type: 'edit'},
        handler: goodsesV1.edit,
        table: 'Goodses'
    },
    '/v1/goodses/delete': {
        permission: {object_type: 'goodses', action_type: 'delete'},
        handler: goodsesV1.delete
    }
});

/**
 * 用户相关Api
 */
const ordersV1 = require('./v1/orders');
const userOrdersV1 = require('./v1/user_orders');
const usersV1 = require('./v1/users');
const accountsV1 = require('./v1/accounts');
const refundsV1 = require('./v1/refunds');
Object.assign(apis, {
    /**
     * 订单管理
     */
    '/v1/orders/analyse': {
        permission: {object_type: 'orders', action_type: 'browse'},
        handler: ordersV1.analyse
    },
    '/v1/orders/browse': {
        permission: {object_type: 'orders', action_type: 'browse'},
        handler: ordersV1.browse
    },
    '/v1/user_orders/analyse': {
        permission: {object_type: 'orders', action_type: 'browse'},
        handler: userOrdersV1.analyse
    },
    '/v1/user_orders/browse': {
        permission: {object_type: 'orders', action_type: 'browse'},
        handler: userOrdersV1.browse
    },
    /**
     * 维权订单管理
     */
    '/v1/refunds/analyse': {
        permission: {object_type: 'orders', action_type: 'browse'},
        handler: refundsV1.analyse
    },
    '/v1/refunds/browse': {
        permission: {object_type: 'orders', action_type: 'browse'},
        handler: refundsV1.browse
    },
    /**
     * 用户管理
     */
    '/v1/users/analyse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: usersV1.analyse
    },
    '/v1/users/browse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: usersV1.browse
    },
    '/v1/users/load': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: usersV1.load
    },
    '/v1/users/add': {
        permission: {object_type: 'users', action_type: 'add'},
        handler: usersV1.add,
        table: 'Users'
    },
    '/v1/users/edit': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.edit,
        table: 'Users'
    },
    '/v1/users/delete': {
        permission: {object_type: 'users', action_type: 'delete'},
        handler: usersV1.delete
    },
    '/v1/users/validate': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: usersV1.validate
    },
    '/v1/users/send_msg': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.sendMsg
    },
    '/v1/users/edit_by_wechat': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.editByWechat
    },
    '/v1/users/agency_change': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.agencyChange
    },
    '/v1/users/agency_cancel': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.agencyCancel
    },
    '/v1/users/alimama_adzones': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.alimamaAdzones
    },
    '/v1/users/alimama_adzone_create': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.alimamaAdzoneCreate
    },
    '/v1/users/image_browse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: usersV1.imageBrowse
    },
    '/v1/users/image_add': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.imageAdd
    },
    '/v1/users/image_edit': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: usersV1.imageEdit
    },

    /**
     * 账号管理
     */
    '/v1/accounts/analyse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: accountsV1.analyse
    },
    '/v1/accounts/browse': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: accountsV1.browse
    },
    '/v1/accounts/load': {
        permission: {object_type: 'users', action_type: 'browse'},
        handler: accountsV1.load
    },
    '/v1/accounts/add': {
        permission: {object_type: 'users', action_type: 'add'},
        handler: accountsV1.add
    },
    '/v1/accounts/edit': {
        permission: {object_type: 'users', action_type: 'edit'},
        handler: accountsV1.edit
    },
    '/v1/accounts/delete': {
        permission: {object_type: 'users', action_type: 'delete'},
        handler: accountsV1.delete
    }
});

/**
 * 财务相关Api
 */
const financesV1 = require('./v1/finances');
const withdrawsV1 = require('./v1/withdraws');
Object.assign(apis, {
    /**
     * 财务
     */
    '/v1/finances/analyse': {
        permission: {object_type: 'finances', action_type: 'browse'},
        handler: financesV1.analyse
    },
    '/v1/finances/browse': {
        permission: {object_type: 'finances', action_type: 'browse'},
        handler: financesV1.browse
    },
    /**
     * 提现
     */
    '/v1/withdraws/analyse': {
        permission: {object_type: 'withdraws', action_type: 'browse'},
        handler: withdrawsV1.analyse
    },
    '/v1/withdraws/browse': {
        permission: {object_type: 'withdraws', action_type: 'browse'},
        handler: withdrawsV1.browse
    },
    '/v1/withdraws/load': {
        permission: {object_type: 'withdraws', action_type: 'browse'},
        handler: withdrawsV1.load
    },
    '/v1/withdraws/status': {
        permission: {object_type: 'withdraws', action_type: 'edit'},
        handler: withdrawsV1.status
    },
    '/v1/withdraws/edit_note': {
        permission: {object_type: 'withdraws', action_type: 'edit'},
        handler: withdrawsV1.editNote
    }
});

/**
 * 建议反馈Api
 */
const suggestionsV1 = require('./v1/suggestions');
const responsesV1 = require('./v1/responses');
Object.assign(apis, {
    /**
     * 建议反馈
     */
    '/v1/suggestions/browse': {
        permission: {object_type: 'suggestions', action_type: 'browse'},
        handler: suggestionsV1.browse
    },
    '/v1/suggestions/load': {
        permission: {object_type: 'suggestions', action_type: 'browse'},
        handler: suggestionsV1.load
    },
    '/v1/suggestions/add': {
        permission: {object_type: 'suggestions', action_type: 'add'},
        handler: suggestionsV1.add,
        table: 'Suggestions'
    },
    '/v1/suggestions/edit': {
        permission: {object_type: 'suggestions', action_type: 'edit'},
        handler: suggestionsV1.edit,
        table: 'Suggestions'
    },
    '/v1/suggestions/delete': {
        permission: {object_type: 'suggestions', action_type: 'delete'},
        handler: suggestionsV1.delete
    },
    /**
     * 自动回复
     */
    '/v1/responses/browse': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: responsesV1.browse
    },
    '/v1/responses/load': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: responsesV1.load
    },
    '/v1/responses/add': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: responsesV1.add
    },
    '/v1/responses/edit': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: responsesV1.edit
    },
    '/v1/responses/delete': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: responsesV1.delete
    }
});

/**
 * 文章相关Api
 */
const articlesV1 = require('./v1/articles');
Object.assign(apis, {
    /**
     * 文章
     */
    '/v1/articles/analyse': {
        permission: {object_type: 'articles', action_type: 'browse'},
        handler: articlesV1.analyse
    },
    '/v1/articles/browse': {
        permission: {object_type: 'articles', action_type: 'browse'},
        handler: articlesV1.browse
    },
    '/v1/articles/load': {
        permission: {object_type: 'articles', action_type: 'browse'},
        handler: articlesV1.load
    },
    '/v1/articles/add': {
        permission: {object_type: 'articles', action_type: 'add'},
        handler: articlesV1.add,
        table: 'Articles'
    },
    '/v1/articles/edit': {
        permission: {object_type: 'articles', action_type: 'edit'},
        handler: articlesV1.edit,
        table: 'Articles'
    },
    '/v1/articles/delete': {
        permission: {object_type: 'articles', action_type: 'delete'},
        handler: articlesV1.delete
    },
    '/v1/articles/image_browse': {
        permission: {object_type: 'articles', action_type: 'browse'},
        handler: articlesV1.imageBrowse
    },
    '/v1/articles/image_add': {
        permission: {object_type: 'articles', action_type: 'edit'},
        handler: articlesV1.imageAdd
    },
    '/v1/articles/image_edit': {
        permission: {object_type: 'articles', action_type: 'edit'},
        handler: articlesV1.imageEdit
    }
});

/**
 * 权限相关Api
 */
const permissionsV1 = require('./v1/permissions');
Object.assign(apis, {
    /**
     * 权限
     */
    '/v1/permissions/find': {
        permission: {object_type: 'permissions', action_type: 'browse'},
        handler: permissionsV1.find
    },
    '/v1/permissions/save': {
        permission: {object_type: 'permissions', action_type: 'edit'},
        handler: permissionsV1.save
    }
});

/**
 * 基础设置Api
 */
const dictsV1 = require('./v1/dicts');
const settingsV1 = require('./v1/settings');
Object.assign(apis, {
    /**
     * 字典
     */
    '/v1/dicts/browse': {
        permission: {object_type: 'dicts', action_type: 'browse'},
        handler: dictsV1.browse
    },
    '/v1/dicts/add': {
        permission: {object_type: 'dicts', action_type: 'add'},
        handler: dictsV1.add
    },
    '/v1/dicts/edit': {
        permission: {object_type: 'dicts', action_type: 'edit'},
        handler: dictsV1.edit
    },
    '/v1/dicts/delete': {
        permission: {object_type: 'dicts', action_type: 'delete'},
        handler: dictsV1.delete
    },
    '/v1/dicts/sort': {
        permission: {object_type: 'dicts', action_type: 'edit'},
        handler: dictsV1.sort
    },
    /**
     * 设置
     */
    '/v1/settings/load': {
        permission: {object_type: 'settings', action_type: 'browse'},
        handler: settingsV1.load
    },
    '/v1/settings/save': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: settingsV1.save
    },
    '/v1/settings/wechat_update': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: settingsV1.wechatUpdate
    },
    '/v1/settings/reindex_goodses_search': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: settingsV1.reindexGoodsesSearch
    },
    '/v1/settings/recapture_user_data': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: settingsV1.recaptureUserData
    },
    '/v1/settings/update_wechat_tags': {
        permission: {object_type: 'settings', action_type: 'edit'},
        handler: settingsV1.updateWechatTags
    }
});

/**
 * 请求转发，权限控制，数据处理
 */
module.exports = function (storage) {
    return function (req, res) {
        let {path, session, body, query} = req;
        let api = apis[path];
        if (api) {
            let {handler, permission, table} = api;
            let user_id = session.user_id;

            let callApi = function () {
                /**
                 * 处理post数据
                 */
                storage.controller.handleBody({
                    req: req,
                    model: table && (storage.models[table] || storage.modelsData[table])
                });

                return Promise.resolve().then(function () {
                    return handler({
                        req: req, res: res, body: body, query: query, session: session, user_id: user_id
                    }, storage);
                }).then(function (response) {
                    if (response.xlsx) {
                        let report = excel.buildExport(
                            [
                                {
                                    name: response.name,
                                    specification: response.specification,
                                    data: response.rows
                                }
                            ]
                        );
                        res.attachment(response.name + '.xlsx');
                        return res.send(report);
                    }
                    return res.json(response === null ? {} : response);
                }, function (err) {
                    if (err) {
                        console.error('\n', err.stack || err.message);
                    }
                    return res.json({success: false, code: 500, message: err && err.message || '请求异常'});
                });
            };
            /**
             * 权限处理
             */
            if (permission) {
                if (!user_id) {
                    return res.status('401').json({success: false, code: 401, message: '未登录'});
                }
                if (permission === true) {
                    return callApi();
                } else {
                    return storage.models.Permissions.checkV2({
                        user_id: user_id, permission: permission
                    }).then(function (result) {
                        if (!result.success) {
                            return res.status('403').json(result);
                        }
                        return callApi();
                    });
                }
            } else {
                return callApi();
            }
        } else {
            res.json({success: false, code: 404, message: '无效API'});
        }
    };
}